from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.db.postgres import get_session
from app.models import DailyTopic
from app.schemas.social_topic import TopicCreate, TopicRead, TopicUpdate
import json


router = APIRouter(prefix="/social/topics", tags=["social-topics"])


@router.post("/", response_model=TopicRead)
async def create_topic(payload: TopicCreate, session: AsyncSession = Depends(get_session)):
    keywords_json = json.dumps(payload.keywords or [])
    obj = DailyTopic(
        topic_id=payload.topic_id,
        topic_name=payload.topic_name,
        topic_description=payload.topic_description or None,
        keywords_json=keywords_json,
        extract_date=payload.extract_date or "1970-01-01",
        relevance_score=None,
        news_count=0,
        processing_status="pending",
    )
    session.add(obj)
    await session.flush()
    await session.refresh(obj)
    await session.commit()
    return TopicRead.model_validate(obj)


@router.get("/", response_model=list[TopicRead])
async def list_topics(session: AsyncSession = Depends(get_session)):
    result = await session.execute(select(DailyTopic).order_by(DailyTopic.extract_date.desc()))
    items = result.scalars().all()
    return [TopicRead.model_validate(x) for x in items]


@router.put("/{id}", response_model=TopicRead)
async def update_topic(id: str, payload: TopicUpdate, session: AsyncSession = Depends(get_session)):
    obj = await session.get(DailyTopic, id)
    if not obj:
        raise HTTPException(status_code=404, detail="话题不存在")
    if payload.topic_name is not None:
        obj.topic_name = payload.topic_name
    if payload.topic_description is not None:
        obj.topic_description = payload.topic_description
    if payload.keywords is not None:
        obj.keywords_json = json.dumps(payload.keywords or [])
    if payload.relevance_score is not None:
        obj.relevance_score = payload.relevance_score
    if payload.processing_status is not None:
        obj.processing_status = payload.processing_status
    await session.flush()
    await session.refresh(obj)
    await session.commit()
    return TopicRead.model_validate(obj)


@router.delete("/{id}")
async def delete_topic(id: str, session: AsyncSession = Depends(get_session)):
    obj = await session.get(DailyTopic, id)
    if not obj:
        raise HTTPException(status_code=404, detail="话题不存在")
    await session.delete(obj)
    await session.commit()
    return {"ok": True}
